package org.dromara.commission.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.commission.domain.bo.LzshAgentInfoRelationBo;
import org.dromara.commission.domain.vo.LzshAgentInfoRelationVo;
import org.dromara.commission.domain.vo.LzshHandworkCommissionImportVo;
import org.dromara.commission.listener.LzshHandworkCommissionImportListener;
import org.dromara.commission.service.ILzshAgentInfoRelationService;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.websocket.dto.WebSocketMessageDto;
import org.dromara.common.websocket.utils.WebSocketUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.commission.domain.vo.LzshHandworkCommissionVo;
import org.dromara.commission.domain.bo.LzshHandworkCommissionBo;
import org.dromara.commission.service.ILzshHandworkCommissionService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 手工佣金
 *
 * @author Lion Li
 * @date 2024-07-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/commission/handworkCommission")
public class LzshHandworkCommissionController extends BaseController {

    private final ILzshHandworkCommissionService lzshHandworkCommissionService;
    private final ILzshAgentInfoRelationService lzshAgentInfoRelationService;
    private final ScheduledExecutorService scheduledExecutorService;
    /**
     * 查询手工佣金列表
     */
    @SaCheckPermission("commission:handworkCommission:list")
    @GetMapping("/list")
    public TableDataInfo<LzshHandworkCommissionVo> list(LzshHandworkCommissionBo bo, PageQuery pageQuery) {
        if (!LoginHelper.isSuperAdmin()) {
            String username = LoginHelper.getUsername();
            bo.setBusinessCode(username);
        }
        return lzshHandworkCommissionService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出手工佣金列表
     */
    @SaCheckPermission("commission:handworkCommission:export")
    @Log(title = "手工佣金", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(LzshHandworkCommissionBo bo, HttpServletResponse response) {
        List<LzshHandworkCommissionVo> list = lzshHandworkCommissionService.queryList(bo);
        ExcelUtil.exportExcel(list, "手工佣金", LzshHandworkCommissionVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param isClear 是否更新已存在数据
     */
    @Log(title = "手工佣金管理", businessType = BusinessType.IMPORT)
    @SaCheckPermission("commission:handworkCommission::import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, @RequestParam("updateSupport") boolean isClear) throws Exception {
        WebSocketMessageDto dto = new WebSocketMessageDto();
        dto.setSessionKeys(List.of(LoginHelper.getUserId()));//设置客户端id,获取 WebSocket 链接

        //获取csv文件的总记录数
        BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
        int lines = 0;
        while (reader.readLine() != null) {
            lines++;
        }
        reader.close();

        LzshHandworkCommissionImportListener importListener = new LzshHandworkCommissionImportListener();
        //开启读取进度监听
        int finalLines = lines - 1;
        scheduledExecutorService.schedule(() -> {
            while (importListener.getReadNum() < finalLines) {
                int per = (int) Math.round(importListener.getReadNum() / (finalLines * 1.0) * 100); // 变成百分比的向下取整
                dto.setMessage("longConnection:$title{正在读取中...请耐心等待}$content{" + per + "}$type{message}");
                WebSocketUtils.publishMessage(dto);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            dto.setMessage("shutDownLongConnection:$title{读取完毕！！！}$content{100}$type{message}");
            WebSocketUtils.publishMessage(dto);
        }, 0 , TimeUnit.SECONDS);

        //查询LzshAgentInfoRelation(验证表)全部数据
        LzshAgentInfoRelationBo bo = new LzshAgentInfoRelationBo();
        List<LzshAgentInfoRelationVo> infoList = lzshAgentInfoRelationService.queryList(bo);
        //查询手工佣金表的全部数据
        LzshHandworkCommissionBo bo1 = new LzshHandworkCommissionBo();
        List<LzshHandworkCommissionVo> hwcList = lzshHandworkCommissionService.queryList(bo1);
        importListener.setInfoList(infoList);
        importListener.setHwcList(hwcList);

        //开始读取导入
        ExcelUtil.importExcel(file.getInputStream(), LzshHandworkCommissionImportVo.class, importListener);

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //文件解析成功
        HashMap<String, List<LzshHandworkCommissionImportVo>> resultData = importListener.getResultData();
        List<LzshHandworkCommissionImportVo> resultList = new ArrayList<>();
        //遍历HashMap的value，将每个List<LzshHandworkCommissionImportVo>的元素加入到resultList
        for (List<LzshHandworkCommissionImportVo> list : resultData.values()) {
            for (LzshHandworkCommissionImportVo item : list) {
                resultList.add(item);
            }
        }

        lzshHandworkCommissionService.insertBatch(resultList, resultList.size());

        return R.ok(importListener.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "手工佣金数据", LzshHandworkCommissionImportVo.class, response);
    }

    /**
     * 获取手工佣金详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("commission:handworkCommission:query")
    @GetMapping("/{id}")
    public R<LzshHandworkCommissionVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(lzshHandworkCommissionService.queryById(id));
    }

    /**
     * 新增手工佣金
     */
    @SaCheckPermission("commission:handworkCommission:add")
    @Log(title = "手工佣金", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody LzshHandworkCommissionBo bo) {
        return toAjax(lzshHandworkCommissionService.insertByBo(bo));
    }

    /**
     * 修改手工佣金
     */
    @SaCheckPermission("commission:handworkCommission:edit")
    @Log(title = "手工佣金", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody LzshHandworkCommissionBo bo) {
        return toAjax(lzshHandworkCommissionService.updateByBo(bo));
    }

    /**
     * 删除手工佣金
     *
     * @param ids 主键串
     */
    @SaCheckPermission("commission:handworkCommission:remove")
    @Log(title = "手工佣金", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(lzshHandworkCommissionService.deleteWithValidByIds(List.of(ids), true));
    }
}
